#include <stdio.h>


struct ListNode {
	int val;
	struct ListNode* next;
};

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    struct ListNode* head = NULL;
    struct ListNode* cur = NULL;
    if (list1 == NULL)
        head = list2;
    if (list2 == NULL)
        head = list1;
    while (list1 && list2) {
        if (list1->val < list2->val) {
            if (cur == NULL) {
                head = cur = list1;
            }
            else
            {
                cur->next = list1;
                cur = cur->next;
            }
            list1 = list1->next;
        }
        else {
            if (cur == NULL) {
                head = cur = list2;
            }
            else
            {
                cur->next = list2;
                cur = cur->next;
            }
            list2 = list2->next;
        }
        if (list1 == NULL)
            cur->next = list2;
        if (list2 == NULL)
            cur->next = list1;
    }
    return head;
}